package org.peppa.utils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class GenerateRandomMessageUtil {

    public static byte[] generateStrData() {
        String verse = getVerse();
//        String verse = "Hello World !!! ";
        return verse.getBytes(StandardCharsets.UTF_8);
    }

    // 发送GET请求
    private static String sendGET(String urlString) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("GET");

        // 添加User-Agent头
        httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0");

        int responseCode = httpURLConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();

            return content.toString();
        } else {
            throw new Exception("GET request failed with response code: " + responseCode);
        }
    }


    private static String getVerse() {
        // 拼接诗句内容
        StringBuilder content = new StringBuilder();
        try {
            // 调用API获取诗句
            String apiUrl = "https://poetrydb.org/random";
            String jsonResponse = sendGET(apiUrl);
            // 解析JSON响应
            JSONArray poemsArray = new JSONArray(jsonResponse);
            if (poemsArray.length() > 0) {
                JSONObject poemObject = poemsArray.getJSONObject(0);
                JSONArray linesArray = poemObject.getJSONArray("lines");
                for (int i = 0; i < linesArray.length(); i++) {
                    content.append(linesArray.getString(i)).append("\n");
                }
            } else {
                System.out.println("No poems found.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content.toString();
    }
}
